import Vue from 'vue'
import VueRouter from 'vue-router'
import config from '@/config'

// 注册路由
Vue.use(VueRouter)

// 同步加载路由模块
import Root from '@/views/common/root'
import Login from '@/views/user/login'
import Home from '@/views/common/home'
import Pages from '@/views/common/pages'

// 异步加载路由模块
const Regist = resolve => require(['@/views/user/regist'], resolve)
const UserCenter = resolve => require(['@/views/user/center'], resolve)
const NotFound = resolve => require(['@/views/common/notfound'], resolve)
const Meal = resolve => require(['@/views/meal/list'], resolve)

// 二级路由
import Findpwd from './findpwd'
import Demos from './demos'

// 路由配置
const routes = [
  { path: '/404', meta: { title: '404' }, component: NotFound },
  { path: '/:site', component: Root, redirect: { name: 'pages' },
    children: [
      { path: 'pages', name: 'pages', meta: { title: '页面列表', requiresAuth: false }, component: Pages },
      { path: 'welcome', name: 'home', meta: { title: '首页', requiresAuth: false }, component: Home },
      { path: 'meal', name: 'meal', meta: { title: '套餐列表', requiresAuth: false }, component: Meal },
      { path: 'login', name: 'login', meta: { title: '登录', requiresAuth: false }, component: Login },
      { path: 'regist', name: 'regist', meta: { title: '注册', requiresAuth: false }, component: Regist },
      { path: 'center', name: 'center', meta: { title: '个人中心', requiresAuth: true }, component: UserCenter },
      Findpwd,
      Demos,
      { path: '*', meta: { title: '404', requiresAuth: true }, component: NotFound },
    ]
  },
]

// 初始化路由对象
const router = new VueRouter({
  routes,
  mode: 'hash',
  base: config.isDev ? '/m/' : '',
  scrollBehavior (to, from, savedPosition) {
    if (savedPosition) {
      return savedPosition
    } else {
      return { x: 0, y: 0 }
    }
  },
})

// 登录验证
// router.beforeEach((to, from, next) => {
//   // 控制是否需要登录
//   if (to.matched.some(record => record.meta.requiresAuth)) {
//     if (!auth.getUser()) {
//       next({
//         path: '/login',
//         query: { redirect: to.fullPath }
//       })
//     } else {
//       next()
//     }
//   } else {
//     next() // 确保一定要调用 next()
//   }
//   next()
// })

router.beforeEach((to, form, next) => {
  console.log(to)
  next()
})

// 设置标题
router.afterEach(route => {
  console.log(route.meta)
  // utils.setTitle(route.meta)
})

export default router
